/* eslint-disable no-unused-vars */
/*
 * Copyright (c) 2022. China Mobile (SuZhou) Software Technology Co.,Ltd. All rights reserved.
 * Lakehouse is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */

import { queryJob } from '@/service/modules/sqlconsole'
import { JobExecResult } from '@/service/modules/sqlconsole/types'
import { useSqlExecTabStore } from '@/store/sqlconsole/sql-exec-tab'
import useStatus from './use-status'

// timer queue
export class TimerQueue {
  private timerSet: any
  private switchStatus: Function
  private $sqlExecTabStore = useSqlExecTabStore()

  constructor(timerSet: any) {
    this.timerSet = timerSet
    this.switchStatus = useStatus().switchStatus
  }

  addTimer(jobId: string, engineType: string): void {
    // interval update job status
    this.timerSet[jobId] = setInterval(() => {
      queryJob(jobId, engineType).then((res: JobExecResult) => {
        const _job = this.$sqlExecTabStore.getExecTabByJob(jobId)

        this.$sqlExecTabStore.updateTab({
          ..._job,
          label: this.switchStatus(res.status) + `(${jobId})`,
          status: res.status,
          columnList: res.columnList,
          resultSet: res.resultSet
        })

        // execute interrupt timer operation in case of success, failure, cancellation, etc
        if (
          res.status === 'FINISHED' ||
          res.status === 'CANCELLED' ||
          res.status === 'SUBMIT_FAILED' ||
          res.status === 'FAILED' ||
          res.status === 'LOST' ||
          res.status === 'UNKNOWN'
        ) {
          window.clearInterval(this.timerSet[jobId])
        }
      })
    }, 4000)
  }

  clearTimer(jobId: string): void {
    window.clearInterval(this.timerSet[jobId])
    if (Object.keys(this.timerSet).length > 0) {
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      const { [jobId as any]: item, ...rest } = this.timerSet
      this.timerSet = rest as any
    }
  }

  clearAllTimer(): void {
    // remove all timer
    ;(Object.keys(this.timerSet) || []).forEach((time) => {
      window.clearInterval(this.timerSet[time])
    })
  }
}
